import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:like_button/like_button.dart';
import 'dart:io';

import 'index.dart';

class TimePage extends GetView<TimeController> {
  const TimePage({super.key});

  // 处理图片加载，支持文件路径和资源路径
  static ImageProvider _getImageProvider(String? path) {
    if (path == null) {
      return AssetImage(Images.ceramic1);
    }

    // 如果是文件路径（以/开头）
    if (path.startsWith('/')) {
      try {
        final file = File(path);
        if (file.existsSync()) {
          return FileImage(file);
        }
      } catch (e) {
        debugPrint('加载文件图片失败: $e');
      }
      return AssetImage(Images.ceramic1);
    }

    // 如果是assets路径
    return AssetImage(path);
  }

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        Positioned.fill(child: Image.asset(Images.startBg, fit: BoxFit.fill)),
        SafeArea(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            width: double.infinity,
            child: Column(
              children: [
                Text(
                  'Ceramic firing',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 30.h),
                _buildTime(),
                SizedBox(height: 28.h),
                Expanded(child: _buildVideo()),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 视频卡片（单个）
  Widget _buildVideoCard(RecommendedVideo video, int index) {
    return GestureDetector(
      onTap: () => controller.goToVideoDetail(index),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(10.r),
        decoration: ShapeDecoration(
          color: const Color(0xFF305CA9),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                  height: 254.h,
                  decoration: ShapeDecoration(
                    image: DecorationImage(
                      image: _getImageProvider(video.thumbnailUrl),
                      fit: BoxFit.cover,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                ),
                // 播放图标
                Positioned.fill(
                  child: Center(
                    child: Icon(
                      IconFontIcons.iconPlay,
                      color: Colors.white,
                      size: 48.sp,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            Row(
              children: [
                _buildViewedUsers(video),
                Spacer(),
                // 收藏
                Obx(() {
                  final videoId = video.id;
                  final isFavorited =
                      videoId != null
                          ? controller.isVideoFavorited(videoId)
                          : false;

                  return LikeButton(
                    size: 24.sp,
                    isLiked: isFavorited,
                    animationDuration: Duration(milliseconds: 800),
                    circleColor: CircleColor(
                      start: Color(0xFFFF5722),
                      end: Color(0xFFFFC107),
                    ),
                    bubblesColor: BubblesColor(
                      dotPrimaryColor: Color(0xFFFF5722),
                      dotSecondaryColor: Color(0xFFFFC107),
                      dotThirdColor: Color(0xFFFF9800),
                      dotLastColor: Color(0xFFF44336),
                    ),
                    likeBuilder: (bool isLiked) {
                      return Icon(
                        isLiked
                            ? IconFontIcons.iconLikeFill
                            : IconFontIcons.iconLike,
                        color: isLiked ? Colors.red : Colors.white,
                        size: 24.sp,
                      );
                    },
                    onTap: (isLiked) async {
                      _handleInteraction(
                        index,
                        InteractionType.favorite,
                        "收藏此视频",
                      );
                      return videoId != null
                          ? controller.isVideoFavorited(videoId)
                          : false;
                    },
                  );
                }),
                SizedBox(width: 27.w),
                // 点赞
                Obx(() {
                  final videoId = video.id;
                  final isLiked =
                      videoId != null
                          ? controller.isVideoLiked(videoId)
                          : false;

                  return LikeButton(
                    size: 24.sp,
                    isLiked: isLiked,
                    animationDuration: Duration(milliseconds: 800),
                    circleColor: CircleColor(
                      start: Color(0xFF00DDFF),
                      end: Color(0xFF0099CC),
                    ),
                    bubblesColor: BubblesColor(
                      dotPrimaryColor: Color(0xFF33B5E5),
                      dotSecondaryColor: Color(0xFF0099CC),
                      dotThirdColor: Color(0xFF00DDFF),
                      dotLastColor: Color(0xFF00AACC),
                    ),
                    likeBuilder: (bool isLiked) {
                      return Icon(
                        isLiked
                            ? IconFontIcons.iconGoodFill
                            : IconFontIcons.iconGood,
                        color: isLiked ? Colors.red : Colors.white,
                        size: 24.sp,
                      );
                    },
                    onTap: (isLiked) async {
                      _handleInteraction(index, InteractionType.like, "点赞此视频");
                      return videoId != null
                          ? controller.isVideoLiked(videoId)
                          : false;
                    },
                  );
                }),
                SizedBox(width: 22.w),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建浏览用户头像组件
  Widget _buildViewedUsers(RecommendedVideo video) {
    if (video.id == null) {
      return SizedBox.shrink();
    }

    return Obx(() {
      final isLoading = controller.isVideoUsersLoading(video.id!);
      final List<User> viewedUsers = controller.getVideoViewedUsers(video.id!);

      if (isLoading) {
        return SizedBox(
          height: 44.h,
          child: Center(
            child: SizedBox(
              width: 20.w,
              height: 20.h,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.white,
              ),
            ),
          ),
        );
      }

      return Row(
        children: [
          // 浏览用户头像
          if (viewedUsers.isNotEmpty) ...[
            SizedBox(
              height: 44.h,
              width: viewedUsers.length > 1 ? 30.w * viewedUsers.length : 44.w,
              child: Stack(
                children: List.generate(
                  viewedUsers.length > 4 ? 4 : viewedUsers.length,
                  (index) => Positioned(
                    left: index * 20.w,
                    child: Container(
                      height: 44.h,
                      width: 44.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ],
                      ),
                      child: ClipOval(
                        child:
                            viewedUsers[index].avatar != null
                                ? Image.asset(
                                  viewedUsers[index].avatar!,
                                  fit: BoxFit.cover,
                                )
                                : Container(
                                  color: Colors.grey[300],
                                  child: Icon(
                                    Icons.person,
                                    size: 25.sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Text(
              'Already viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ] else ...[
            // 没有浏览用户时显示
            Container(
              height: 44.h,
              width: 44.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
              child: Center(
                child: Icon(Icons.add, size: 20.sp, color: Colors.white),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              'No one viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ],
      );
    });
  }

  // 处理交互（点赞/收藏）
  void _handleInteraction(int index, InteractionType type, String actionName) {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 使用通用方法检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage:
          type == InteractionType.like
              ? 'You need to login to like this video.'
              : 'You need to login to favorite this video.',
      onLoggedIn: () {
        // 已登录，执行相应操作
        controller.selectVideo(index);
        if (type == InteractionType.like) {
          controller.toggleLike();
        } else {
          controller.toggleFavorite();
        }
      },
    );
  }

  // 推荐视频
  Widget _buildVideo() {
    return Column(
      children: [
        Align(
          alignment: Alignment.centerLeft,
          child: Text(
            'Ceramic production video',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
        SizedBox(height: 10.h),
        // 视频卡片列表
        Expanded(
          child: Obx(() {
            if (controller.recommendedVideos.isEmpty) {
              return Center(
                child: CircularProgressIndicator(color: Colors.white),
              );
            }

            return ListView.separated(
              itemCount: controller.recommendedVideos.length,
              separatorBuilder: (context, index) => SizedBox(height: 16.h),
              itemBuilder: (context, index) {
                final video = controller.recommendedVideos[index];
                return _buildVideoCard(video, index);
              },
            );
          }),
        ),
      ],
    );
  }

  // 烧制按钮
  Widget _buildTime() {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Container(
          width: double.infinity,
          height: 82.h,
          decoration: ShapeDecoration(
            color: const Color(0xFF305CA9),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.r),
            ),
          ),
        ),
        Positioned(
          bottom: 10.h,
          left: 14.w,
          child: CircleAvatar(
            radius: 44.r,
            backgroundImage: AssetImage(Images.timer),
            backgroundColor: Colors.transparent,
          ),
        ),
        // 文本提示
        Positioned(
          bottom: 21.h,
          left: 115.w,
          child: SizedBox(
            width: 143.w,
            child: Text(
              'Start your own cooking at a fixed time',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                height: 1.43,
              ),
            ),
          ),
        ),
        // 前往烧制
        Positioned(
          bottom: 18.h,
          right: 16.w,
          child: GestureDetector(
            onTap: () {
              // 获取用户服务
              final userService = Get.find<UserService>();

              // 检查登录状态并跳转
              userService.checkLoginThenExecute(
                loginRequiredMessage:
                    'You need to login to use the firing timer',
                onLoggedIn: () {
                  Get.toNamed(Routes.firing);
                },
              );
            },
            child: Container(
              width: 90.w,
              height: 48.h,
              decoration: ShapeDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.50, -0.00),
                  end: Alignment(0.50, 1.00),
                  colors: [const Color(0xFF4580DD), const Color(0xFF5592F1)],
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(37.r),
                ),
              ),
              child: Center(
                child: Text(
                  'To burn',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 17.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<TimeController>(
      init: TimeController(),
      id: "time",
      builder: (_) {
        return Scaffold(body: _buildView());
      },
    );
  }
}
